const express = require("express");
const router = express.Router();
const passport = require("passport");
const InfoStream = require("../../../models/InfoStream");
const auth = passport.authenticate("jwt", { session: false });
const errorHandler = require("../../../middlewares/errorHandler");

// @route  GET api/infoStream
// @desc   获取首页信息流数据
// @access Private
router.get("/", auth, async (req, res) => {
  try {
    const infoStreams = await InfoStream.find()
      .select("_id user title imageUrl date comments")
      .populate("user.id", "_id name avatar");

    const response = infoStreams.map((info) => ({
      _id: info._id,
      user: info.user.id,
      title: info.title,
      imageUrl: info.imageUrl,
      date: info.date,
      commentCount: info.comments.length,
    }));

    res.status(200).json({ success: true, data: response });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/infoStream/detail/:id
// @desc   获取信息流的详细内容
// @access Private
router.get("/detail/:id", auth, async (req, res) => {
  try {
    const infoStream = await InfoStream.findById(req.params.id).select(
      "_id user title content imageUrl date"
    );

    if (!infoStream) {
      return res.status(404).json({ success: false, error: "信息流未找到" });
    }

    res.status(200).json({ success: true, data: infoStream });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  POST api/infoStream/add
// @desc   添加首页信息流
// @access Private
router.post("/add", auth, async (req, res) => {
  try {
    const { title, content, imageUrl } = req.body;
    const newInfoStream = new InfoStream({
      user: {
        id: req.user._id,
        name: req.user.name,
        avatar: req.user.avatar,
      },
      title,
      content,
      imageUrl,
    });
    const infoStream = await newInfoStream.save();
    res.status(201).json({ success: true, data: infoStream });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  PUT api/infoStream/edit
// @desc   编辑信息流
// @access Private
router.put("/edit", auth, async (req, res) => {
  try {
    const { _id, title, content, imageUrl } = req.body;
    const infoStream = await InfoStream.findById(_id);

    if (!infoStream) {
      return res.status(404).json({ success: false, error: "信息流未找到" });
    }

    if (infoStream.user.id.toString() !== req.user._id.toString()) {
      return res.status(401).json({ success: false, error: "用户未授权" });
    }

    infoStream.title = title;
    infoStream.content = content;
    infoStream.imageUrl = imageUrl;

    const updatedInfoStream = await infoStream.save();
    res.status(200).json({ success: true, data: updatedInfoStream });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  DELETE api/infoStream/delete
// @desc   删除信息流
// @access Private
router.delete("/delete", auth, async (req, res) => {
  try {
    const { _id } = req.body;
    const infoStream = await InfoStream.findById(_id);

    if (!infoStream) {
      return res.status(404).json({ success: false, error: "信息流未找到" });
    }

    if (infoStream.user.id.toString() !== req.user._id.toString()) {
      return res.status(401).json({ success: false, error: "用户未授权" });
    }

    await infoStream.remove();
    res.status(200).json({ success: true, data: "信息流已删除" });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  POST api/infoStream/comment
// @desc   添加评论
// @access Private
router.post("/comment", auth, async (req, res) => {
  try {
    const { infoId, contentText, replyTo } = req.body;
    const infoStream = await InfoStream.findById(infoId);

    if (!infoStream) {
      return res.status(404).json({ success: false, error: "信息流未找到" });
    }

    const newComment = {
      user: {
        id: req.user._id,
        name: req.user.name,
        avatar: req.user.avatar,
      },
      contentText,
      date: new Date(),
    };

    if (replyTo) {
      const parentComment = infoStream.comments.id(replyTo);
      if (!parentComment) {
        return res
          .status(404)
          .json({ success: false, error: "被回复的评论未找到" });
      }
      parentComment.replyList.push(newComment);
    } else {
      infoStream.comments.push(newComment);
    }

    await infoStream.save();
    res.status(201).json({ success: true, data: infoStream });
  } catch (err) {
    errorHandler(res, err);
  }
});

router.delete("/comment", auth, async (req, res) => {
  try {
    const { infoId, commentId } = req.body;
    const infoStream = await InfoStream.findById(infoId);
    if (!infoStream) {
      return res.status(404).json({ success: false, error: "信息流未找到" });
    }
    const comment = infoStream.comments.id(commentId);
    if (!comment) {
      return res.status(404).json({ success: false, error: "评论未找到" });
    }
    comment.remove(); // 删除评论及其所有回复
    await infoStream.save();
    res.status(200).json({ success: true, data: infoStream });
  } catch (err) {
    errorHandler(res, err);
  }
});

router.delete("/reply", auth, async (req, res) => {
  try {
    const { infoId, commentId, replyId } = req.body;

    const infoStream = await InfoStream.findById(infoId);
    if (!infoStream) {
      return res.status(404).json({ success: false, error: "信息流未找到" });
    }
    const comment = infoStream.comments.id(commentId);
    if (!comment) {
      return res.status(404).json({ success: false, error: "评论未找到" });
    }
    const reply = comment.replyList.id(replyId);
    if (!reply) {
      return res.status(404).json({ success: false, error: "回复未找到" });
    }
    reply.remove(); // 删除特定回复
    await infoStream.save();
    res.status(200).json({ success: true, data: infoStream });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/infoStream/comments
// @desc   查询评论
// @access Private
router.post("/comments", auth, async (req, res) => {
  try {
    const { infoId } = req.body;
    const infoStream = await InfoStream.findById(infoId).select("comments");

    if (!infoStream) {
      return res.status(404).json({ success: false, error: "信息流未找到" });
    }

    const commentsWithReplyCount = infoStream.comments.map((comment) => ({
      ...comment.toObject(),
      replyCount: comment.replyList.length,
    }));

    res.status(200).json({ success: true, data: commentsWithReplyCount });
  } catch (err) {
    errorHandler(res, err);
  }
});

module.exports = router;
